<?php
/*
 * СПВ
 **/
class SPLoader
{	
	static private $classes=array();
	static private $libs_folder='libs';
	static private $models_folder='models';
	
	
	static private function splitCamelCase($string, $lower = true)
	{
	  $array = preg_split('/([A-Z][^A-Z]*)/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
	  if ($lower) 
	  {
		$array = array_map(strtolower, $array);
	  }
	  return $array;
	}
	
	static public function defineClass($name, $path)
	{
		self::$classes[$name]=$path;
	}
	
	static public function enableAutoload()
	{
		spl_autoload_register(array(self, 'autoload'));
	}
	
	static private function autoload($name)
	{
		if ( self::loadClass($name) ) return true;
		if ( self::loadModel($name) ) return true;
		return false;
	}
	
	static public function getSpPath()
	{
		return dirname(__FILE__).'/';
	}
	
	static public function setIncludePath($path)
	{
		set_include_path($path);
	}
	
	static public function setLibsFolder($name)
	{
		self::$libs_folder=$name;
	}
	
	static public function setModelsFolder($name)
	{
		self::$models_folder=$name;
	}
	
	
	static public function loadFunctions($name)
	{
		include_once(self::getSpPath().'functions/'.$name.'.php');
	}
	
	
	static public function loadClass($name)
	{
		$full_path=get_include_path().'/'.self::$libs_folder.'/'.$name;
		if( file_exists($full_path) && is_file($full_path) ) 
		{
			//echo $full_path.'<br />';
			require_once($full_path);
			return true;
		}
		
		$full_path=get_include_path().'/'.self::$libs_folder.'/'.self::$classes[$name];
		if( file_exists($full_path) && is_file($full_path) && array_key_exists($name, self::$classes) ) 
		{
			//echo $full_path.'<br />';
			require_once($full_path);
			return true;
		}
		
		$full_path=get_include_path().'/'.self::$libs_folder.'/'.strtolower(str_replace('_', '/', $name)).'.php';
		if( file_exists($full_path) && is_file($full_path)  ) 
		{
			//echo $full_path.'<br />';
			require_once($full_path);
			return true;
		}
		//echo 'not loaded';
		return false;
	}
	
	static public function loadModel($name)
	{
		$full_path=get_include_path().'/'.self::$models_folder.'/'.$name;
		if( file_exists($full_path) && is_file($full_path) ) 
		{
			//echo $full_path.'<br />';
			require_once($full_path);
			return true;
		}
		
		$from_camel_name=implode('_',self::splitCamelCase($name));
		$full_path=get_include_path().'/'.self::$models_folder.'/'.$from_camel_name.'.php';
		if( file_exists($full_path) && is_file($full_path) ) 
		{
			//echo $full_path.'<br />';
			require_once($full_path);
			return true;
		}
		
		$full_path=get_include_path().'/'.self::$models_folder.'/base/'.$from_camel_name.'.php';
		if( file_exists($full_path) && is_file($full_path) ) 
		{
			//echo $full_path.'<br />';
			require_once($full_path);
			return true;
		}
		//echo '<br />not loaded<br />';
		return false;
	}
}